import 'package:cbec_app/utils/ThemeConfig.dart';
import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:cbec_app/routes/routes.dart';
import 'package:cbec_app/utils/Tools.dart';

import '../../../pages/goods/binding/goods_detail_binding.dart';
import '../../../pages/goods/view/goods_detail_page.dart';
import 'decoration_new_zone_ctr.dart';

/// 店铺装修-新人专区
class DecorationNewZone extends StatefulWidget {
  /// 区域配置
  final Map<String, dynamic> info;

  const DecorationNewZone({
    super.key,
    required this.info,
  });

  @override
  State<DecorationNewZone> createState() => _DecorationNewZoneState();
}

class _DecorationNewZoneState extends State<DecorationNewZone> {
  late DecorationNewZoneCtr controller;

  @override
  void initState() {
    super.initState();
    String timestamp = DateTime.now().millisecondsSinceEpoch.toString();
    controller = Get.put(DecorationNewZoneCtr(), tag: timestamp);
  }

  @override
  Widget build(BuildContext context) {
    controller.fetchData(widget.info);
    return Obx(() {
      if (controller.displayedGoodsList.isEmpty) {
        return const SizedBox();
      }
      return Stack(
        children: [
          // 最底部的背景图片
          const BackgroundImage(),
          // 其余三个组件在 BackgroundImage 上从上到下排列并垂直居中
          Center(
            child: Column(
              mainAxisSize: MainAxisSize.max,
              children: [
                // 标题部分
                if (widget.info['show_title'] == '1') TopCenterTitle(info: widget.info),
                // 中间部分的商品列表
                CenterGooodsList(
                  marketingGoods: controller.displayedGoodsList.map((item) => item!.toJson()).toList(),
                  onProductCardPressed: (item) {
                    final id = item['goodsId'];
                    Get.to(
                      () => GoodsDetailPage(flag: id), // 使用函数懒加载页面实例
                      routeName: '${Routes.goodsDetail}?unique=${DateTime.now().millisecondsSinceEpoch}',
                      arguments: {"id": id}, // 传递其它参数
                      binding: GoodsDetailBinding(flag: id), // 将 tag 参数传递给绑定类
                    );
                  },
                  onPressed: () {
                    controller.refreshData();
                  },
                ),
                // 底部间距
                const SizedBox(height: 10), // 添加10的底部间距
              ],
            ),
          ),
        ],
      );
    });
  }
}

class BackgroundImage extends StatelessWidget {
  final String? imageUrl;

  const BackgroundImage({super.key, this.imageUrl});

  @override
  Widget build(BuildContext context) {
    return Positioned.fill(
      child: ClipRRect(
        borderRadius: BorderRadius.circular(20), // 设置圆角半径为 20
        child: imageUrl != null
            ? Image.network(
                imageUrl!,
                fit: BoxFit.cover,
              )
            : Container(
                color: Tools.fromHex('#E74C2C'), // 默认背景颜色
              ),
      ),
    );
  }
}

class TopCenterTitle extends StatelessWidget {
  final Map<String, dynamic> info;
  const TopCenterTitle({super.key, required this.info});

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(10),
      child: Text(info['title_value'] ?? '', style: const TextStyle(fontSize: 24, fontWeight: FontWeight.bold, color: Colors.white)),
    );
  }
}

class CenterGooodsList extends StatelessWidget {
  final List<dynamic>? marketingGoods;
  final Function(dynamic)? onProductCardPressed; // 添加回调
  final VoidCallback? onPressed; // 回调属性

  const CenterGooodsList({
    super.key,
    this.marketingGoods,
    this.onProductCardPressed,
    this.onPressed,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 375.w - 20.w,
      padding: const EdgeInsets.all(10), // 添加10的内边距
      decoration: BoxDecoration(
        color: Colors.white, // 背景颜色
        borderRadius: BorderRadius.circular(20), // 添加20的圆角
      ),
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            mainAxisSize: MainAxisSize.min, // 根据内容高度调整
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              // 商品卡片部分
              marketingGoods != null && marketingGoods!.isNotEmpty
                  ? Row(
                      children: marketingGoods!.map<Widget>((item) {
                        // 确保每个 item 包含了所需字段以生成 ProductCard
                        return GestureDetector(
                          onTap: () {
                            if (onProductCardPressed != null) {
                              onProductCardPressed!(item); // 调用回调
                            }
                          },
                          child: ProductCard(
                            imageUrl: item['mainImage'] ?? '', // 获取图片链接或使用占位符
                            name: item['commodityName'] ?? '',
                            currentPrice: item['seckillPrice'] ?? 0.0, // 获取当前价格或默认值
                            originalPrice: item['price'] ?? 0.0, // 获取原始价格或默认值
                          ),
                        );
                      }).toList(),
                    )
                  : const SizedBox(), // 如果 marketingGoods 为 null 或空
            ],
          ),
          const SizedBox(height: 15), // 卡片和按钮之间的间距
          Center(
            child: BottomRefreshChange(
              onPressed: () {
                if (onPressed != null) {
                  onPressed!();
                }
              },
            ),
          )
        ],
      ),
    );
  }
}

class BottomRefreshChange extends StatelessWidget {
  final VoidCallback? onPressed; // 回调属性

  const BottomRefreshChange({
    super.key,
    this.onPressed,
  });

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(15),
      child: TextButton(
        onPressed: () {
          if (onPressed != null) {
            onPressed!(); // 调用回调函数
          }
        },
        style: TextButton.styleFrom(
          padding: EdgeInsets.zero, // 去掉内边距
          minimumSize: const Size(0, 0), // 去掉默认的最小大小
          tapTargetSize: MaterialTapTargetSize.shrinkWrap, // 收缩点击区域
        ),
        child: Row(
          mainAxisSize: MainAxisSize.min,
          children: [
            // 左边的图片
            Image.asset(
              'assets/images/search_ic_re.png',
              width: 20,
              height: 20,
            ),
            // 图片和文字之间的间距
            const SizedBox(width: 8),
            // 右边的文字
            Text(
              '换一批',
              style: TextStyle(fontSize: 16, color: Tools.fromHex('#C8C8C8')), // 可以自定义文字颜色
            ),
          ],
        ),
      ),
    );
  }
}

// 商品卡片小组件
class ProductCard extends StatelessWidget {
  final String imageUrl;
  final String name;
  final double currentPrice;
  final double originalPrice;

  const ProductCard({
    required this.imageUrl,
    required this.name,
    required this.currentPrice,
    required this.originalPrice,
    super.key,
  });

  @override
  Widget build(BuildContext context) {
    return Container(
      width: 110.w,
      padding: const EdgeInsets.all(5),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(5.0),
        border: Border.all(color: Tools.fromHex('#C8C8C8'), width: 0.5),
      ),
      child: Column(
        children: [
          // 商品图片
          Center(
            child: Image.network(
              imageUrl,
              width: 90.w,
              height: 90.w,
            ),
          ),
          // 商品名称
          SizedBox(
            width: 90.w,
            child: Align(
              alignment: Alignment.center, // 设置子组件在容器中左对齐
              child: Text(
                name,
                style: const TextStyle(
                  fontSize: 14,
                  fontWeight: FontWeight.bold,
                ),
                maxLines: 1, // 限制最多显示2行
                overflow: TextOverflow.ellipsis, // 超出部分显示省略号
                softWrap: true, // 允许换行
              ),
            ),
          ),
          Row(
            mainAxisSize: MainAxisSize.min, // 只包裹子组件
            crossAxisAlignment: CrossAxisAlignment.start, // 子组件从左边开始对齐
            children: [
              Text(
                '¥$currentPrice',
                style: TextStyle(color: Tools.fromHex('#ec544d'), fontSize: 14),
              ),
              const SizedBox(width: 4),
              Text(
                '¥$originalPrice',
                style: const TextStyle(
                  decoration: TextDecoration.lineThrough,
                  color: ThemeConfig.subTextColor,
                  fontSize: 12,
                ),
              ),
            ],
          ),
          const SizedBox(height: 4),
        ],
      ),
    );
  }
}
